package ar.com.cema.methodology.analyzer.services.repository.impl;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ar.com.cema.methodology.analyzer.model.PersistentObject;
import ar.com.cema.methodology.analyzer.services.persistence.SimpleDAO;
import ar.com.cema.methodology.analyzer.services.repository.SimpleObjectRepository;

@Repository
public class SimpleObjectRepositoryImpl implements SimpleObjectRepository {

	@Autowired
	private SimpleDAO simpleDAO;
	
	@Override
	@SuppressWarnings("unchecked")
	public <T extends PersistentObject> Set<T> findAll(Class<T> clazz) {
		List<T> list = simpleDAO.createCriteria(clazz).list();
		TreeSet<T> set = new TreeSet<T>();
		set.addAll(list);
		return set;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T extends PersistentObject> T save(T o) {
		return (T) simpleDAO.save(o);
	}

	public void setSimpleDAO(SimpleDAO simpleDAO) {
		this.simpleDAO = simpleDAO;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T extends PersistentObject> Set<T> findAllWithAscendingOrder(Class<T> clazz) {
		List<T> list = simpleDAO.createCriteria(clazz).addOrder(Order.asc("id")).list();
		TreeSet<T> set = new TreeSet<T>();
		set.addAll(list);
		return set;
	}

	@Override
	public <T extends PersistentObject> Integer count(Class<T> clazz) {
		Long count = (Long) simpleDAO.createCriteria(clazz).setProjection(Projections.count("id")).uniqueResult();
		return count.intValue();
	}
}
